#!/data/Software/mydan/perl/bin/perl -I/data/Software/mydan/CI/lib -I/data/Software/mydan/CI/private/lib
use strict;
use warnings;
use JSON;
use Logs;
use LWP::UserAgent;
use Encode;
use Util;

$| ++;

=head1 SYNOPSIS

    db => $mysql,
    logs => 日志对象
=cut

return sub
{
    my %param = @_;
    my ( $logs, $projectid, $calljob, $version, $taginfo ) = @param{qw( logs projectid calljob version taginfo )};
    print '=' x 75, "\n";
    print "calljob($param{calljob})...\n";

    $logs = Logs->new( 'code.build.send.calljob' ) unless $logs;

    my $ua = LWP::UserAgent->new();
    $ua->agent('Mozilla/9 [en] (Centos; Linux)');

    #HTTP::Message content must be bytes at
    my $bytes = encode_utf8($param{calljob}); 
    $calljob = $bytes;
    $bytes = encode_utf8($param{taginfo}); 
    $taginfo = $bytes;

    my %env = eval{ Util::envinfo( qw( appkey appname envname envname.job ) )};
    $logs->die( "fromat error $@" ) if $@;

    $ua->default_header( map{ $_ => $env{$_} }qw( appname appkey) );
 
    $ua->timeout( 10 );
    $ua->default_header ( 'Cache-control' => 'no-cache', 'Pragma' => 'no-cache' );

    my $url = "http://api.job.open-c3.org/task/$projectid/job/byname";
    my $res = $ua->post( $url, 
	Content => JSON::to_json( +{ jobname => $calljob, variable => +{ version => $version, taginfo => $taginfo, ci => "n-$env{envname}" } } ), 
	'Content-Type' => 'application/json' 
    );

    my $cont = $res->content;
    $logs->die( "calljob fail: $cont" ) unless $res->is_success;

    my $data = eval{JSON::from_json $cont};
    $logs->die( "calljob fail: $cont : no json $@" ) if $@;

    $logs->die( "calljob fail: $cont : stat fail" )  unless $data->{stat};

    printf "call job ok: jobuuid:%s\n", $data->{uuid};
}
